//app.js
var Util = require('utils/util.js');
App({
  aData: {
    show: false
  },
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  getUserInfo: function (isrefresh, cb) {
    var that = this
    if (isrefresh != true && this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      wx.login({
        success: function (res) {
          var code = res.code
          //console.info(code);
          wx.getUserInfo({
            withCredentials: true,
            success: function (res) {
              var rawData = res['rawData'];
              var signature = res['signature'];
              var encryptData = res['encryptData'];
              var encryptedData = res['encryptedData']; //注意是encryptedData不是encryptData...坑啊
              var iv = res['iv'];
              console.info(res);
              Util.Login({
                "theme": that.globalData.scene,
                "code": code,
                "rawData": rawData,
                "signature": signature,
                "encryptData": encryptData,
                'iv': iv,
                'encryptedData': encryptedData,
                'share_code': that.globalData.sharecode
              }, function (re) {
                //console.info(res);
                if (re.code == 200) {
                  wx.setStorage({
                    key: 'token',
                    data: re.token,
                    success: function (rr) {
                      if (rr.errMsg =='setStorage:ok'){
                        typeof cb == "function" && cb(re.token);
                      }
                    }
                  })
                }
                else {
                  Util.showMsgDialog("登录失败" + re.msg);
                }
              }, function (err) {
                Util.showMsgDialog("登录失败");
              })
            },
            fail: function (err) {
              console.log("wx.getUserInfo", err);
            }
          })
        },
        fail: function (err) {
          console.log("wx.login", err);
        }
      });
    }
  },
  globalData: {
    userInfo: null,
    IMGHOST: "https://wx.himayi.cn",
  }
})